<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue 3 动态class切换</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <style>
        .active { color: green; }
        .error { color: red; }
        .text-danger { font-weight: bold; }
        .static { background-color: lightgray; }
    </style>
</head>
<body>
    <div id="app">
        <!-- 使用对象语法绑定类 -->
        <div :class="{ active: isActive, error: hasError }">Object Syntax</div>

        <!-- 使用计算属性绑定类 -->
        <div :class="classObject">Computed Property</div>

        <!-- 使用静态类和动态类结合 -->
        <div class="static" :class="{ active: isActive }">Static and Dynamic Classes</div>
    </div>

    <script>
        const { createApp, ref, computed } = Vue;

        createApp({
            setup() {
                // 响应式数据
                const isActive = ref(false);
                const hasError = ref(false);

                // 在模板中直接定义的对象
                const classObject = computed(() => ({
                    active: isActive.value && !hasError.value,
                    'text-danger': hasError.value
                }));

                // 切换类的方法
                function toggleClass() {
                    isActive.value = !isActive.value;
                    hasError.value = !hasError.value;
                }

                // 每隔一秒切换类状态
                setInterval(toggleClass, 1000);

                return { isActive, hasError, classObject };
            }
        }).mount('#app');
    </script>
</body>
</html>
